package com.silverhaze.diamond.client.ui.table.model;

import com.silverhaze.diamond.client.settings.Settings;
import com.silverhaze.diamond.client.settings.SettingsStorage;
import com.silverhaze.diamond.client.utils.ServiceException;

import javax.swing.table.DefaultTableModel;
import java.util.List;

/**
 * © Ivan Babanin (14.07.2007 2:42:51)
 * This part of code is strictly confidential.
 * © Magnificent Software Inc.
 */
public abstract class AbstractServiceTableModel<T> extends DefaultTableModel {
    private int colCount;
    private int rowCount;
    private Object[][] data;
    private Settings settings;
    private String[] columnName;

    public abstract T getObjectAtRow(int row);

    public abstract void fillData(List data);

    protected abstract void createFields();

    public AbstractServiceTableModel() {
        createFields();
    }

    public AbstractServiceTableModel(List data) {
        createFields();
        fillData(data);
    }

    public boolean isCellEditable(int row, int column) {
        return false;
    }

    public String getColumnName(int c) {
        if (c > getColumnName().length) {
            throw new IllegalArgumentException(String.valueOf(c));
        } else {
            return getColumnName()[c];
        }
    }

    public Object getValueAt(int i, int j) {
        check(i, j);
        return getData()[i][j];
    }

    private void check(int i, int j) {
        if (i < 0 || i >= getRowCount() || j < 0 || j >= getColumnCount()) {
            throw new ServiceException("TABLE MODEL", "i or j out of bounds of array");
        }
    }

    public void refreshModel() {
        fireTableDataChanged();
//        fireTableStructureChanged();
    }

    public abstract void refreshModelAll();

    public int getColumnCount() {
        return colCount;
    }

    protected void setColCountSize(int colCount) {
        this.colCount = colCount;
    }

    public int getRowCount() {
        return rowCount;
    }

    protected void setRowCountSize(int rowCount) {
        this.rowCount = rowCount;
    }

    public String[] getColumnName() {
        return columnName;
    }

    public void setColumnName(String[] columnName) {
        this.columnName = columnName;
    }

    public Object[][] getData() {
        return data;
    }

    public void setData(Object[][] data) {
        this.data = data;
    }

    public void setCell(int i, int j, Object o) {
        check(i, j);
        data[i][j] = o;
    }

    public Settings getSettings() {
        if (settings == null) {
            settings = SettingsStorage.getSettings();
        }

        return settings;
    }
}

